<template>
	<view class="add-order-page flat-page">
		<!-- 1. 顶部导航栏 -->
		<view class="flat-nav">
			<image src="/static/icons/back.png" class="back-icon" mode="aspectFit" @click="handleBack" />
			<text class="nav-title">{{ isEditing ? '编辑订单' : '添加订单' }}</text>
			<view class="nav-placeholder"></view>
		</view>

		<!-- 2. 表单区域 -->
		<form class="form-container flat-form" @submit.prevent="handleSubmit">
			<!-- 表单分组：联系人信息 -->
			<view class="form-section flat-section">
				<text class="section-title flat-title">联系人信息</text>

				<!-- 联系人姓名 -->
				<view class="form-item flat-form-item">
					<text class="label flat-label">联系人</text>
					<input type="text" class="input flat-input" v-model="orderForm.contactName"
						placeholder="请输入联系人姓名" />
					<text class="error-message" v-if="formErrors.contactName">{{ formErrors.contactName }}</text>
				</view>

				<!-- 联系人电话 -->
				<view class="form-item flat-form-item">
					<text class="label flat-label">联系电话</text>
					<input type="tel" class="input flat-input" v-model="orderForm.contactPhone" placeholder="请输入联系电话" />
					<text class="error-message" v-if="formErrors.contactPhone">{{ formErrors.contactPhone }}</text>
				</view>
			</view>

			<!-- 表单分组：订单基本信息 -->
			<view class="form-section flat-section">
				<text class="section-title flat-title">订单信息</text>
				<!-- 订单金额 -->
				<view class="form-item flat-form-item">
					<text class="label flat-label">订单金额</text>
					<view class="input-wrapper">
						<text class="currency-symbol">¥</text>
						<input type="number" class="input flat-input" v-model.number="orderForm.amount"
							placeholder="请输入金额" />
					</view>
					<text class="error-message" v-if="formErrors.amount">{{ formErrors.amount }}</text>
				</view>

				<!-- 订单状态 -->
				<view class="form-item flat-form-item">
					<text class="label flat-label">订单状态</text>
					<view class="select-wrapper flat-select" @click="showStatusDrawer = true">
						<text class="select-text">{{ orderForm.status || '请选择订单状态' }}</text>
						<image src="/static/icons/arrow-down.png" class="arrow-icon" mode="aspectFit" />
					</view>
					<text class="error-message" v-if="formErrors.status">{{ formErrors.status }}</text>
				</view>

				<!-- 支付时间 -->
				<view class="form-item flat-form-item">
					<text class="label flat-label">支付时间</text>
					<picker mode="date" :value="orderForm.payTime" start="2000-01-01" end="2030-12-31" fields="day"
						@change="onDateChange" @click.prevent>
						<view class="picker-wrapper flat-select">
							<text class="picker-text">{{ orderForm.payTime || '请选择支付时间' }}</text>
							<image src="/static/icons/arrow-down.png" class="arrow-icon" mode="aspectFit" />
						</view>
					</picker>
				</view>

				<!-- 备注 -->
				<view class="form-item flat-form-item">
					<text class="label flat-label">备注</text>
					<textarea class="textarea flat-textarea" v-model="orderForm.remark" placeholder="请输入备注信息（选填）"
						rows="2"></textarea>
				</view>
			</view>

			<!-- 表单按钮区域 -->
			<view class="form-actions">
				<button type="submit" class="submit-btn flat-btn primary-btn" @click="handleSubmit" :disabled="loading">
					<text v-if="!loading">保存订单</text>
					<text v-if="loading">保存中...</text>
				</button>
				<button class="cancel-btn flat-btn" @click="handleBack" :disabled="loading">
					取消
				</button>
			</view>
		</form>

		<!-- 3. 订单状态选择抽屉 -->
		<view class="drawer status-drawer flat-drawer" :class="{ show: showStatusDrawer }">
			<view class="drawer-header flat-drawer-header">
				<text class="drawer-title">选择订单状态</text>
				<image src="/static/icons/close.png" class="drawer-close" mode="aspectFit"
					@click="showStatusDrawer = false" />
			</view>
			<view class="drawer-body flat-drawer-body">
				<view class="drawer-item flat-drawer-item" v-for="status in statusOptions" :key="status"
					:class="{ active: orderForm.status === status }" @click="selectStatus(status)">
					<text class="item-text">{{ status }}</text>
					<image src="/static/icons/check.png" class="item-check" mode="aspectFit"
						v-if="orderForm.status === status" />
				</view>
			</view>
			<view class="drawer-footer flat-drawer-footer">
				<button class="drawer-btn confirm-btn" @click="confirmStatusSelection" :disabled="loading">
					确定
				</button>
			</view>
		</view>

		<!-- 4. 抽屉遮罩层 -->
		<view class="drawer-mask" :class="{ show: showStatusDrawer }" @click="showStatusDrawer = false"></view>
	</view>
</template>

<script>
	import {
		createOrder,
		updateOrder
	} from '@/https/order.js';
	export default {
		data() {
			return {
				// 1. 页面状态和标识
				isEditing: false,
				groupId: '',
				// 2. 订单表单数据
				orderForm: {
					id: 0,
					amount: '',
					status: '',
					payTime: '',
					contactName: '',
					contactPhone: '',
					remark: ''
				},
				// 3. 状态选择器数据
				showStatusDrawer: false,
				statusOptions: ['待支付', '已支付', '已取消', '已完成', '已退款'],
				// 表单验证状态
				formErrors: {
					status: '',
					contactName: ''
				},
				// 5. 加载状态
				loading: false
			};
		},
		onLoad(options) {
			// 获取页面参数
			this.groupId = options.groupId || '';
			const orderStr = options.order || '';

			if (orderStr) {
				try {
					// 如果有订单数据，则为编辑模式
					const order = JSON.parse(decodeURIComponent(orderStr));
					this.isEditing = true;
					// 赋值给表单
					this.orderForm.id = order.id || 0;
					// 订单号由后台生成，无需赋值
					this.orderForm.amount = order.amount || '';
					this.orderForm.status = order.status || '';
					this.orderForm.payTime = this.formatDateForInput(order.payTime || '');
					this.orderForm.contactName = order.contactName || '';
					this.orderForm.contactPhone = order.contactPhone || '';
					this.orderForm.remark = order.remark || '';
				} catch (error) {
					console.error('解析订单数据失败:', error);
					uni.showToast({
						title: '订单数据解析失败',
						icon: 'none'
					});
				}
			} else {
				// 新增模式
				// 设置默认状态
				this.orderForm.status = '待支付';
				// 设置当前日期为支付时间
				this.orderForm.payTime = this.getTodayDate();
			}
		},
		methods: {
			// 订单号由后台自动生成，移除前端生成逻辑

			// 获取今天的日期字符串，格式为YYYY-MM-DD
			getTodayDate() {
				const today = new Date();
				const year = today.getFullYear();
				const month = String(today.getMonth() + 1).padStart(2, '0');
				const day = String(today.getDate()).padStart(2, '0');
				return `${year}/${month}/${day}`;
			},

			// 格式化日期为输入框可用格式
			formatDateForInput(dateStr) {
				if (!dateStr || dateStr == '0001/01/01T00:00:00' || dateStr == '0001-01-01T00:00:00') return '';
				try {
					// 处理不同格式的日期字符串，确保iOS兼容性
					const normalizedDateStr = dateStr.replace(/-/g, '/'); // 将 - 替换为 / 以提高iOS兼容性
					const date = new Date(normalizedDateStr);
					const year = date.getFullYear();
					const month = String(date.getMonth() + 1).padStart(2, '0');
					const day = String(date.getDate()).padStart(2, '0');
					return `${year}/${month}/${day}`; // 前端显示使用 / 格式，提高iOS兼容性
				} catch (e) {
					console.error('日期格式化错误:', e);
					return '';
				}
			},

			// 表单验证
			validateForm() {
				let isValid = true;

				// 重置错误提示
				Object.keys(this.formErrors).forEach(key => {
					this.formErrors[key] = '';
				});

				// 只验证必填字段：联系人和订单状态
				// 验证订单状态
				if (!this.orderForm.status) {
					this.formErrors.status = '请选择订单状态';
					isValid = false;
				}

				// 验证联系人
				if (!this.orderForm.contactName.trim()) {
					this.formErrors.contactName = '联系人不能为空';
					isValid = false;
				}

				return isValid;
			},

			// 处理表单提交
			async handleSubmit() {
				// 表单验证
				if (!this.validateForm()) {
					// 显示第一个错误
					const firstErrorField = Object.keys(this.formErrors).find(key => this.formErrors[key]);
					if (firstErrorField) {
						uni.showToast({
							title: this.formErrors[firstErrorField],
							icon: 'none'
						});
					}
					return;
				}

				this.loading = true;
				try {
					// 构建提交数据
					// 处理日期格式：将前端显示的格式转换为后台需要的 yyyy-MM-dd 格式
					let formattedPayTime = this.orderForm.payTime;
					if (formattedPayTime) {
						// 将 / 替换为 - 以符合后台要求
						formattedPayTime = formattedPayTime.replace(/\//g, '-');
					}

					const submitData = {
						id: this.orderForm.id,
						amount: this.orderForm.amount,
						status: this.getStatusValue(this.orderForm.status),
						payTime: formattedPayTime,
						contactName: this.orderForm.contactName,
						contactPhone: this.orderForm.contactPhone,
						remark: this.orderForm.remark,
						tourGroupId: parseInt(this.groupId),
						openId: ""
					};

					let res;
					if (this.isEditing) {
						// 编辑模式 - 更新订单
						res = await updateOrder(submitData);
					} else {
						// 新增模式 - 创建订单
						res = await createOrder(submitData);
					}

					if (res) {
						uni.showToast({
							title: this.isEditing ? '订单更新成功' : '订单添加成功',
							icon: 'success'
						});

						// 延迟返回上一页，让用户看到成功提示
						setTimeout(() => {
							uni.navigateBack({
								delta: 1
							});
						}, 1500);
					} else {
						uni.showToast({
							title: this.isEditing ? '订单更新失败' : '订单添加失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('保存订单失败:', error);
					uni.showToast({
						title: '网络异常，请重试',
						icon: 'none'
					});
				} finally {
					this.loading = false;
				}
			},

			// 根据状态文本获取对应的枚举值
			getStatusValue(statusText) {
				const statusMap = {
					'待支付': 0,
					'已支付': 1,
					'已取消': 2,
					'已完成': 3,
					'已退款': 4
				};
				return statusMap[statusText] || 0;
			},

			// 状态选择器相关方法
			selectStatus(status) {
				this.orderForm.status = status;
			},

			confirmStatusSelection() {
				this.showStatusDrawer = false;
			},

			// 日期选择器处理方法
			onDateChange(e) {
				const value = e.detail.value;
				// 转换格式为前端显示格式 yyyy/MM/dd
				this.orderForm.payTime = value.replace(/-/g, '/');
			},

			// 返回上一页
			handleBack() {
				uni.navigateBack({
					delta: 1
				});
			}
		}
	};
</script>

<style scoped>
	@import './addOrder.css';
</style>